package lwk.juc.lock;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:lwk
 * @create: 2022-08-10 22:06
 * @Description: 经典卖票
 */
public class SafeTicketDemo2 {
    public static void main(String[] args) {
        Ticket2 ticket = new Ticket2();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    ticket.sell();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"A窗口").start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    ticket.sell();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"B窗口").start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    ticket.sell2();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"C窗口").start();


    }
}

class Ticket2 {
    private int ticketNums = 200;
    ReentrantLock lock = new ReentrantLock(true);

    public void sell() throws InterruptedException {
        lock.lock();
        try {
            Thread.sleep(10);
            if (ticketNums>0) {
                System.out.println(Thread.currentThread().getName()+"卖出了第=="+ticketNums+"==张票，剩余===="+--ticketNums);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void sell2() throws InterruptedException {

        // 5秒获取不到锁，返回FALSE
        boolean b = lock.tryLock(5, TimeUnit.SECONDS);

        if (b) {
            try {
                Thread.sleep(10);
                if (ticketNums>0) {
                    System.out.println(Thread.currentThread().getName()+"卖出了第=="+ticketNums+"==张票，剩余===="+--ticketNums);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(b);
        }

    }
}